package org.example.mini_spring;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

public class BeanDefinition {

    private final String name;

    private final Constructor<?> constructor;

    private final Method postConstructMethod;

    private final List<Field> autowireFields;

    private final Class<?> beanType;

    public BeanDefinition(Class<?> beanType) {

        this.beanType = beanType;

        Component component = beanType.getDeclaredAnnotation(Component.class);

        this.name = component.name().isEmpty() ? beanType.getSimpleName() : component.name();

        try {
            this.constructor = beanType.getConstructor();
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        this.postConstructMethod = Arrays.stream(beanType.getDeclaredMethods())
                .filter(e->e.isAnnotationPresent(PostConstruct.class))
                .findFirst()
                .orElse(null);

        this.autowireFields = Arrays.stream(beanType.getDeclaredFields())
                .filter(e->e.isAnnotationPresent(Autowired.class))
                .toList();

    }

    public String getName() {
        return name;
    }

    public Constructor<?> getConstructor() {
        return constructor;
    }

    public Method getPostConstructMethod() {
        return postConstructMethod;
    }

    public List<Field> getAutowireFields() {
        return autowireFields;
    }

    public Class<?> getBeanType() {
        return beanType;
    }
}
